package com.dianrui.moonfire.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;
import com.dianrui.moonfire.Constant;
import com.dianrui.moonfire.R;
import com.dianrui.moonfire.util.StringUtils;
import com.dianrui.moonfire.util.Url;

import butterknife.BindView;
import butterknife.OnClick;
/**
 * Description:客服的webview
 * User: luoziyin
 * Date: 2020-8-17
 */
public class CustomerWebViewActivity extends BaseActivity {
    private boolean isSuccess = false;
    private boolean isError = false;
    private LinearLayout ll_control_error;

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.webview)
    WebView webview;

    @BindView(R.id.show_webview_layout)
    LinearLayout showWebviewLayout;



    @Override
    public int getContentViewId() {
        return R.layout.webview;
    }

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    public void initView() {
        customInit(true);
        webview.post(new Runnable() {
            @Override
            public void run() {
                String areaId = "";
                String member_id = "";
                if (StringUtils.isEmpty(SPUtils.getInstance().getString("area_id"))) {
                    areaId = "0";
                } else {
                    areaId = SPUtils.getInstance().getString("area_id");
                }
                if (StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
                    member_id = "";
                } else {
                    member_id = SPUtils.getInstance().getString("member_id");
                }
                webview.loadUrl(Url.BASE_URL + Constant.service+"?member_id="+member_id+"&area_id="+areaId);
                title.setText("客服");
                ll_control_error = (LinearLayout) findViewById(R.id.ll_control_error);
                Button errorBtn=ll_control_error.findViewById(R.id.online_error_btn_retry);
                TextView errorTitle=ll_control_error.findViewById(R.id.title);
                ImageView backimg=ll_control_error.findViewById(R.id.back);
                errorTitle.setText("找不到网页");
                errorBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ll_control_error.setVisibility(View.GONE);
                        showWebviewLayout.setVisibility(View.VISIBLE);
                        webview.reload();
                    }
                });
                backimg.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
                WebSettings webSetting = webview.getSettings();
                webSetting.setJavaScriptEnabled(true);
                webSetting.setUseWideViewPort(true);
                webview.setWebViewClient(new WebViewClient() {
                    @Override
                    public void onPageFinished(WebView view, String url) {
                        super.onPageFinished(view, url);
                        if (!isError) {
                            isSuccess = true;
                            //回调成功后的相关操作
                            ll_control_error.setVisibility(View.GONE);
                            showWebviewLayout.setVisibility(View.VISIBLE);
                            webview.setVisibility(View.VISIBLE);
                        } else {
                            isError = false;
                            webview.setVisibility(View.GONE);
                            showWebviewLayout.setVisibility(View.GONE);
                            ll_control_error.setVisibility(View.VISIBLE);
                        }

                    }


                    @Override
                    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                        super.onReceivedError(view, errorCode, description, failingUrl);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            return;
                        }
                        isError = true;
                        isSuccess = false;
                        //6.0以下执行
                        webview.setVisibility(View.GONE);
                        showWebviewLayout.setVisibility(View.GONE);
                        ll_control_error.setVisibility(View.VISIBLE);

                    }


                    @Override
                    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                        super.onReceivedError(view, request, error);
                        isError = true;
                        isSuccess = false;
                        //6.0以上执行
                        webview.setVisibility(View.GONE);
                        showWebviewLayout.setVisibility(View.GONE);
                        ll_control_error.setVisibility(View.VISIBLE);

                    }


                    @TargetApi(Build.VERSION_CODES.N)
                    @Override
                    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                        final Uri uri = request.getUrl();
                        if (uri.toString().startsWith("tel:")) {
                            if (Build.VERSION.SDK_INT >= 23) {
                                if (ContextCompat.checkSelfPermission(CustomerWebViewActivity.this, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
                                    startActivity(new Intent(Intent.ACTION_CALL, uri));
                                } else {
                                    ActivityCompat.requestPermissions(CustomerWebViewActivity.this, new String[]{Manifest.permission.CALL_PHONE}, 1);
                                }
                            } else {
                                startActivity(new Intent(Intent.ACTION_CALL, uri));
                            }
                        } else {
                            //Handle Web Urls
                            view.loadUrl(uri.toString());
                        }
                        return true;
                    }


                    @Override
                    public boolean shouldOverrideUrlLoading(WebView view, String url) {
                        if (url.startsWith("tel:")) {
                            if (Build.VERSION.SDK_INT >= 23) {
                                if (ContextCompat.checkSelfPermission(CustomerWebViewActivity.this, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
                                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(url));
                                    startActivity(intent);
                                } else {
                                    ActivityCompat.requestPermissions(CustomerWebViewActivity.this, new String[]{Manifest.permission.CALL_PHONE}, 1);
                                }
                            } else {
                                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(url));
                                startActivity(intent);
                            }
                        }else {
                            view.loadUrl(url);
                        }
                        return true;
                    }
                });
            }
        });

    }

    @Override
    public void initData() {

    }


    @OnClick(R.id.back)
    public void onViewClicked() {
      finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();

        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (webview != null) {
            webview.onResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (webview != null) {
            webview.onPause();
        }
    }


    @OnClick({R.id.back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;

                default:
                    break;

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (webview != null) {
            webview.clearCache(true);
            webview.stopLoading();
            //防止系统在3.x的手机，在缩放按钮未完全关闭时候退出的闪退
            webview.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (webview != null) {
                        webview.destroy();
                        webview = null;
                    }
                }
            }, 3000);
        }
    }
}
